package com.wu.webflux3.config;

import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity;
import org.springframework.security.config.web.server.ServerHttpSecurity;
import org.springframework.security.core.userdetails.ReactiveUserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.server.SecurityWebFilterChain;
import org.springframework.security.web.server.authentication.RedirectServerAuthenticationSuccessHandler;
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatchers;

import com.wu.webflux3.customUserService.CustomReactiveUserDetailsService;

@EnableWebFluxSecurity
public class WebFluxConfig {

	@Bean
	public PasswordEncoder initPasswordEncoder() {
		return new BCryptPasswordEncoder();
	}

	@Bean
	public ReactiveUserDetailsService userDetailsService() {
		return new CustomReactiveUserDetailsService();
	}

	@Bean
	public SecurityWebFilterChain springSecurityFilterChain2(ServerHttpSecurity http) {
		ServerHttpSecurity build = http.formLogin().loginPage("/index")
				.requiresAuthenticationMatcher(
						ServerWebExchangeMatchers.pathMatchers(HttpMethod.POST, "/account/login"))
				.authenticationSuccessHandler(new RedirectServerAuthenticationSuccessHandler("/hello")).and()
				.authorizeExchange().pathMatchers("/js/**", "/actuator/**", "/index", "/logout").permitAll()
				.pathMatchers("/hello").hasAnyAuthority("ROLE_USER").pathMatchers("/**").authenticated().and().logout()
				.and().csrf().disable();
		return build.build();
	}
}
